package com.leyou.auth.service.impl;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.constants.RedisConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.leyou.auth.constants.JwtConstants.COOKIE_NAME;

@Service
public class UserAuthServiceImpl implements UserAuthService {
    @Autowired
    UserClient userClient;
    @Autowired
    JwtUtils jwtUtils;
    @Override
    public void login(String username, String password, HttpServletResponse response) {
        //远程调用
        try {
            UserDTO userDTO = userClient.queryUserByUsernameAndPassword(username, password);
            if (userDTO==null){
                throw  new LyException(400,"用户名或密码错误");
            }
            //准备用户信息
            UserDetails userDetails = UserDetails.of(userDTO.getId(), userDTO.getUsername());
            //生成jwt
            String jwt = jwtUtils.createJwt(userDetails);
            //写入cookie
            writeCookie(response,jwt);
        } catch (FeignException e) {
            throw new LyException(e.status(), e.contentUTF8());
        }

    }
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //获取cookie
        String cookieValue = CookieUtils.getCookieValue(request, COOKIE_NAME);
        //检查时效
        Payload payload=null;
        try {
             payload = jwtUtils.parseJwt(cookieValue);
        } catch (Exception e) {
           //无效 不用做 直接返回
            return;
        }
        //如果有 删除
        CookieUtils.deleteCookie(JwtConstants.COOKIE_NAME,JwtConstants.DOMAIN,response);
        //删除redis中的jti
        UserDetails userDetail = payload.getUserDetail();
     stringRedisTemplate.delete(RedisConstants.JTI_KEY_PREFIX + userDetail.getId());

    }

    private void writeCookie(HttpServletResponse response, String jwt) {
        Cookie cookie = new Cookie(COOKIE_NAME, jwt);
        // cookie的作用域
        cookie.setDomain(JwtConstants.DOMAIN);
        // 是否禁止JS操作cookie，避免XSS攻击
        cookie.setHttpOnly(true);
        // cookie有效期，-1就是跟随当前会话，浏览器关闭就消失
        cookie.setMaxAge(-1);
        // cookie作用的路径，/代表一切路径
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
